import 'dart:async';

import 'package:flutter/material.dart';
import 'package:surfaceim/common/apis/apis.dart';
import 'package:surfaceim/common/entities/entities.dart';
import 'package:surfaceim/common/store/store.dart';
import 'package:surfaceim/common/routes/names.dart';
import 'package:surfaceim/common/utils/utils.dart';
import 'package:surfaceim/common/widgets/widgets.dart';
import 'package:get/get.dart';
import 'package:phone_form_field/phone_form_field.dart';

import 'index.dart';

class SignUpController extends GetxController {
  SignUpController();

  /// obs 响应式变量 才写入 state
  final state = SignUpState();

  /// 业务变量

  // 禁用倒计时
  late int countDown = 60;
  Timer? undateTimer;

  // 重新发送 -- 可用标志
  late bool afresh = false;

  // 注册流程步进
  late int page = 0;

  // 页控制器
  late final PageController pageController;

  // 是否已点击同意协议
  late bool isRead = false;

  // 输入控制器
  late PhoneNumber mobileController = PhoneNumber(nsn: '', isoCode: 'CN');

  /// 业务事件

  // 提交手机号和验证码
  Future<void> mobileLogin({
    required String verificationCode,
  }) async {
    Loading.show();
    UserLoginRequestEntity params = UserLoginRequestEntity(
      mobile: mobileController.nsn,
      type: 1,
      code: verificationCode,
    );

    UserLoginResponseEntity userLoginResponse = await UserAPI.mobileLogin(
      params: params,
    );

    if (userLoginResponse.code.toString() == '1') {
      // 存 token
      String? token = userLoginResponse.info!.token;
      await UserStore.to.setToken(token!);
      // 存完 token 立即更新用户画像
      await UserStore.to.getProfile();
      Loading.dismiss();
      Get.toNamed(AppRoutes.BASIC_INFORMATION);
    } else {
      toastInfo(msg: '验证码不对还是手机号不对?');
      Loading.dismiss();
    }
  }

  // tab栏动画
  void handleNavBarTap(int index) {
    page = index;
    pageController.animateToPage(page,
        duration: const Duration(milliseconds: 200), curve: Curves.ease);
  }

  // 切换注册流程
  void handlePageChanged(int page) {
    page = page;
  }

  // 点击已阅读
  userAgreement(value) {
    isRead = value;
    update(['Agreement']);
  }

  // 返回上一页
  handleNavPop() {
    Get.back();
  }

  // 忘记密码
  handleFogotPassword() {
    toastInfo(msg: '忘记密码');
  }

  // 开始倒计时
  void startCountdown() {
    // 倒计时
    // undateTimer.isActive?undateTimer.cancel()  // 取消定时器
    if (undateTimer != null) {
      undateTimer!.cancel(); // 取消定时器
    } else {
      undateTimer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (countDown <= 0) {
          afresh = false;
          update(['countDown']);
          countDown = 60;
          undateTimer!.cancel(); // 取消定时器
        } else {
          if (!afresh) {
            afresh = true;
          }
          countDown--;
          update(['countDown']);
        }
      });
    }
  }

  // 异步获取验证码
  void getVerificationCode({
    bool isAfresh = false,
  }) async {
    // return;
    if (!isRead) {
      toastInfo(msg: '请先阅读 《用户协议》 《个人信息保护》 ');
      return;
    }

    if (mobileController.nsn.length == 0) {
      toastInfo(msg: '请输入手机号');
      return;
    }

    if (!duIsMobile(mobileController.nsn)) {
      toastInfo(msg: '请输入正确手机号');
      return;
    }

    Loading.show();

    UserRegisterRequestEntity params = UserRegisterRequestEntity(
      mobile: mobileController.nsn,
    );

    UserRegisterResponseEntity verification = await UserAPI.code(
      params: params,
    );

    Loading.dismiss();
    if (verification.code == 1) {
      toastInfo(msg: '发送成功');
      if (isAfresh) {
        handleNavBarTap(1);
      }
      startCountdown();
    } else {
      toastInfo(msg: verification.msg);
    }
  }

  // 重新获取验证码
  afreshCode({isAfresh: true}) async {
    getVerificationCode();
  }

  // 执行注册操作

  handleSignUp() async {
    getVerificationCode(isAfresh: true);
  }

  /// 生命周期

  //
  @override
  void onInit() {
    print('注册页面初始化');
    pageController = new PageController(initialPage: page);
    super.onInit();
  }

  // 页面载入完成
  @override
  void onReady() {
    super.onReady();
  }

  @override
  void dispose() {
    super.dispose();
    pageController.dispose();
  }

  @override
  void onClose() {
    if (undateTimer != null) {
      undateTimer!.cancel(); // 取消定时器
    }
    super.onClose();
  }
}
